
/*
 * TriggerRunner
 * A thread class which calls AbstractTrigger.execute() once it has
 * finished its time poling
 */

public class TriggerRunner extends Thread
{

	public TriggerRunner(AbstractTrigger trigger, int ms)
	{
		this.itsAbstractTrigger = trigger;
		this.runtimeMs = ms;
	}
	
	public void go()
	{
		// call halt first, effectively reseting the trigger timer
		halt();
		start();
	}
	
	public void halt()
	{
		// set the keepRunning attribute will brake out of the polling in the run() method
		keepRunning = false;
		try 
		{
			// wait for the thread to complete nicely
			this.join();
		} 
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}
		keepRunning = true;
	}
	
	public void run()
	{
		timeLeftMs = runtimeMs;
		
		while(keepRunning && timeLeftMs > 0)
		{
			try
			{
				Thread.sleep(pollInterval);
			} 
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			
			timeLeftMs -= pollInterval;
		}
		if(keepRunning)
		{
			itsAbstractTrigger.execute();
		}
		keepRunning = true;
	}
		
	private boolean keepRunning = true;
	private int runtimeMs, timeLeftMs;
	private int pollInterval = 50;
	private AbstractTrigger itsAbstractTrigger;
}
